package linearList;

/**
 * Created by eason on 2017/11/18.
 * 单链表 --实现
 */
public class MySiglelyLinkedList<E> implements MyList<E> {
    private Node<E> first;
    private int  size;

    @Override
    public Integer size() {
        return this.size;
    }

    @Override
    public Object get(int i) {
        checkRange(i);

        return null;
    }


    /***
     *   尾插入法  链表顺序和插入顺序一致
     * @param object
     * @return
     */
    @Override
    public boolean add(E object) {
       Node  newNode =new Node<E>(object,null);
       if(first ==null){
           first =newNode;
       }else {
           Node<E> head = first;
           while (head.next != null) {
               head = head.next;
           }
          head.next = newNode;
       }
       size++;
        return true;
    }

    /**
     * 在某个位置插入元素
     * @param object
     * @param position
     * @return
     */
    public  boolean add(E object,int position){
        checkRange(position);
        Node<E> prev = null;
        for(int i=0; i<=position-1;i++) {
            if (i == 0) {
                prev = first;
            } else {
                prev = prev.next;
            }
        }
            Node  newNode = new Node<E>(object,prev.next);
            prev.next= newNode;
        size ++;
        return true;
    }

    public  String  display(){
        StringBuilder stringBuilder = new StringBuilder();
        Node  node=first;
        while(node!=null){
             stringBuilder.append(node.data);
             if(node.next!=null){
                 stringBuilder.append(",");
             }
             node =node.next;
        }
        return  stringBuilder.toString();
    }


    /***
     * 头插入法，链表顺序和插入顺序相反
     * @param object
     * @return
     */
    public Boolean  addHead(E object){
        Node  newNode =new Node<E>(object,null);
        newNode.next = first;
        first = newNode;
        size++;
        return true;
    }

    @Override
    public boolean remove(int i) {
        return false;
    }

    @Override
    public boolean empty() {
        first =null;
        size =0;
        return true;
    }

    //节点对象
    private class Node<E>{
        private E data; //数据
        private Node<E> next; //指向下一个节点
        Node(E date,Node<E> next){
            this.data = date;
            this.next = next;
        }

    }

    private  void  checkRange(int  i){
        if(i<0 ||i>=size){
            throw  new IndexOutOfBoundsException();
        }
    }
}
